//
//  HomeViewController.swift
//  ERecycle-Shop
//
//  Created by abb on 16/8/10.
//  Copyright © 2016年 abb. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let cloudKey = "07577911646537ec9b006d56c6880289"
let tableid = "57ac8a8eafdf520b8952c106"
let MylocationReuseIndentifier = "MylocationReuseIndentifier"
let PointReuseIndentifier = "PointReuseIndentifier"
class HomeViewController: AbbBaseViewController {

    /// 订单模型
    var orders:[Order]? {
        didSet {
            mapView.removeAnnotations(pointAnnotations)
            var pas = [MAPointAnnotation]()
            for order in orders! {
                let pointAnnotation = OrderPointAnnotation()
                pointAnnotation.coordinate = order.locationPoint!.toCLLocationCoordinate2D()
                pointAnnotation.order = order
                pas.append(pointAnnotation)
            }
            pointAnnotations = pas
        }
    }
    /// 订单标记
    var pointAnnotations:[MAPointAnnotation]? {
        didSet {
            mapView.addAnnotations(pointAnnotations)
        }
    }
    /// 当前定位点
    var location:(MAMapPoint,AMapGeoPoint)? {
        didSet {
            if oldValue != nil && location != nil {
                distanceMoved = MAMetersBetweenMapPoints(oldValue!.0
                    , location!.0)
            }
            if oldValue == nil && location != nil {
                searchOrders()
            }
        }
    }
    /// 移动距离
    var distanceMoved:CLLocationDistance? {
        didSet {
            print(distanceMoved)
        }
    }
    
    var refreshOrder:Bool = false {
        didSet {
            searchOrders()
        }
    }
    /// 透明navBar
    override var userTransparentNavigationBar: Bool {
        return false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        orderDescriptionView.seeDetailsCallBack = { [weak self] (user,order) in
            let vc = OrderInfoViewController()
            vc.user = user
            vc.order = order
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        orderDescriptionView.orderDidReceivedCallBack = { 
            self.refreshOrder = true
        }
    }
    override func viewDidAppear(animated: Bool) {
        iconView.sd_setImageWithURL(User.loadUser()!.userImageUrl, forState: UIControlState.Normal, placeholderImage: UIImage(named: "rightItem"), options: .RefreshCached)
    }
    
    /**
     加载UI
     */
    private func setupUI() {
        // 添加子控件
        view.addSubview(mapView)
        view.addSubview(locationBtn)
        view.addSubview(zoomBtnView)
        view.addSubview(orderDescriptionView)
        // 布局子控件

        locationBtn.snp_makeConstraints { (make) in
            make.left.equalTo(self.view).offset(20)
            make.bottom.equalTo(orderDescriptionView.snp_top).offset(-20)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        zoomBtnView.snp_makeConstraints { (make) in
            make.right.equalTo(self.view).offset(-20)
            make.bottom.equalTo(orderDescriptionView.snp_top).offset(-20)
            make.size.equalTo(CGSize(width: 35, height: 70))
        }
        orderDescriptionView.snp_makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(0)
        }
        // 添加响应事件
        zoomBtnView.addZoomBtn.addTarget(self, action: #selector(addZoomLevel), forControlEvents: .TouchUpInside)
        zoomBtnView.subZoomBtn.addTarget(self, action: #selector(subZoomLevel), forControlEvents: .TouchUpInside)

        self.navigationItem.titleView = searchView
        let rightItem = UIBarButtonItem(customView: iconView)
        self.navigationItem.leftBarButtonItem = rightItem
    }
    
    /**
     搜索订单
     */
    func searchOrders() {
        request.center = location?.1
        search.AMapCloudPOIAroundSearch(request)
    }
    /**
     增加缩放
     */
    func addZoomLevel() {
        
        print(self.navigationController?.navigationBar.userInteractionEnabled)
        print(self.navigationController?.navigationBar)
        let newZoomeLevel = mapView.zoomLevel + 1
        mapView.setZoomLevel(newZoomeLevel, animated: true)
    }
    /**
     减小缩放
     */
    func subZoomLevel() {
        let newZoomeLevel = mapView.zoomLevel - 1
        mapView.setZoomLevel(newZoomeLevel, animated: true)
    }
    /**
     点击头像
     */
    func clickIcon() {
        let vc = MyViewController()
        vc.user = User.loadUser()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func clickTextField() {
        
    }
    /**
     定位到当前位置
     */
    func loadLocation() {
        mapView.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)
        
    }
    
    // MARK: - 懒加载
    /// 高德地图
    private lazy var mapView:MAMapView = {
        let mp = MAMapView(frame: UIScreen.mainScreen().bounds)
        mp.delegate = self
        mp.showsScale = false
        mp.showsCompass = false
        mp.showsUserLocation = true
        mp.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)
        mp.pausesLocationUpdatesAutomatically = false
        mp.allowsBackgroundLocationUpdates = false
        mp.zoomLevel = 16
        mp.maxZoomLevel = 20
        mp.minZoomLevel = 13
        return mp
    }()
    /// 头像item
    private lazy var iconView:UIButton = {
        let iconView = UIButton(imageName: "user_default", bgColor: UIColor.tintColor())
        iconView.frame.size = CGSize(width: 40, height: 40)
        iconView.layer.cornerRadius = 20
        iconView.layer.masksToBounds = true
        iconView.addTarget(self, action: #selector(clickIcon), forControlEvents: .TouchUpInside)
        return iconView
    }()
    /// 搜索
    private lazy var searchView:UIView = {
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 255, height: 44))
        searchBar.delegate = self
        searchBar.barTintColor = UIColor.tintColor()
        searchBar.placeholder = "搜索分类/关键字"
        print(searchBar.subviews[0].isKindOfClass(NSClassFromString("UISearchBarBackground")!))
        for view in searchBar.subviews[0].subviews {
            
            if view.isKindOfClass(NSClassFromString("UISearchBarBackground")!) {
                view.removeFromSuperview()
                break
            }
        }
        let searchView = UIView(frame: CGRect(x: 0, y: 0, width: 768, height: 44))
        searchView.addSubview(searchBar)
        return searchView
    }()
    
    /// 头部视图
//    private lazy var topView:TopView = {
//        let tv = TopView()
//        tv.layer.cornerRadius = 5
//        tv.layer.borderWidth = 0.5
//        tv.layer.borderColor = UIColor.lightGrayColor().CGColor
//        return tv
//    }()
    /// 定位按钮
    private lazy var locationBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "location"), forState: .Normal)
        btn.layer.cornerRadius = 4
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor.lightGrayColor().CGColor
        btn.backgroundColor = UIColor.whiteColor()
        btn.addTarget(self, action: #selector(loadLocation), forControlEvents: .TouchUpInside)
        return btn
    }()
    /// 缩放btn
    private lazy var zoomBtnView:ZoomButtonView =  ZoomButtonView()
    /// 订单简介view
    private lazy var orderDescriptionView:OrderDescriptionView = {
        let odv = OrderDescriptionView()
        odv.layer.shadowRadius = 2
        odv.layer.shadowOpacity = 0.3
        odv.layer.shadowColor = UIColor.blackColor().CGColor
        return odv
    }()
    
    /// 搜索
    private lazy var search:AMapSearchAPI = {
        let search = AMapSearchAPI()
        search.delegate = self
        return search
    }()
    /// 请求
    private lazy var request:AMapCloudPOIAroundSearchRequest = {
        let request = AMapCloudPOIAroundSearchRequest()
        request.tableID = tableid
        request.filter = ["status:0"]
        return request
    }()

}
extension HomeViewController:UISearchBarDelegate {
    
}

extension HomeViewController:MAMapViewDelegate {
    func mapView(mapView: MAMapView!, didUpdateUserLocation userLocation: MAUserLocation!, updatingLocation: Bool) {
        if (updatingLocation && distanceMoved > 200 && distanceMoved != nil) || location == nil {
            let latitude = CGFloat(userLocation.coordinate.latitude)
            let longitude = CGFloat(userLocation.coordinate.longitude)
            self.location = (MAMapPointForCoordinate(userLocation.coordinate),AMapGeoPoint.locationWithLatitude(latitude, longitude: longitude))
        }
        if !updatingLocation && mapView.viewForAnnotation(userLocation) != nil {
            mapView.viewForAnnotation(userLocation).image = UIImage(named: "userPosition")!.rotatedByRadians(DegreesToRadians(CGFloat(userLocation.heading.trueHeading)))
        }
    }
    func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {
        // 订单标记
        print(annotation)
        if annotation.isKindOfClass(OrderPointAnnotation.self) {
            var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(PointReuseIndentifier)
            if annotationView == nil {
                annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: PointReuseIndentifier)

            }
            annotationView.image = UIImage(named: "pin")
            print(annotationView.subviews)
            
            return annotationView
        }
        return nil
    }
    func mapView(mapView: MAMapView!, didAddAnnotationViews views: [AnyObject]!) {
        let view = views[0] as! MAAnnotationView
        // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
        if view.annotation.isKindOfClass(MAUserLocation.self) {
            let pre = MAUserLocationRepresentation()
            pre.image = UIImage(named: "userPosition")
            self.mapView.updateUserLocationRepresentation(pre)
        }
    }
    func mapView(mapView: MAMapView!, didSelectAnnotationView view: MAAnnotationView!) {
        
        if view.isKindOfClass(CustomAnnotationView.self) {
            mapView.setCenterCoordinate(view.annotation.coordinate, animated: true)
            orderDescriptionView.order = (view.annotation as! OrderPointAnnotation).order
            UIView.animateWithDuration(0.25, animations: {
                self.orderDescriptionView.snp_updateConstraints(closure: { (make) in
                    make.height.equalTo(125)
                })
                self.view.layoutIfNeeded()
            })
        }
    }
    func mapView(mapView: MAMapView!, didDeselectAnnotationView view: MAAnnotationView!) {
        if view.isKindOfClass(CustomAnnotationView.self) {
            UIView.animateWithDuration(0.25, animations: {
                self.orderDescriptionView.snp_updateConstraints(closure: { (make) in
                    make.height.equalTo(0)
                })
                self.view.layoutIfNeeded()
            })
        }
    }
}
extension HomeViewController:AMapSearchDelegate {
    func onCloudSearchDone(request: AMapCloudSearchBaseRequest!, response: AMapCloudPOISearchResponse!) {
        if response.POIs.count == 0 {
            return
        }
        if orders == nil {
            orders = [Order]()
        } else {
            orders?.removeAll()
        }
        for POI in response.POIs {
            let order = Order(poi: POI)
            orders?.append(order)
        }
    }
}